<template>
  <div class="components-container feature-out">
    <div ref="searchDiv" class="filter-container">
      <el-select
        size="small"
        v-model="tableQuery.dataSource"
        clearable
        placeholder="请选择数据源"
        class="filter-item"
        style="width: 200px;"
      >
        <el-option
          v-for="(item, index) in data_source"
          :key="index"
          :label="item"
          :value="item"
        ></el-option>
      </el-select>
      <el-select
        size="small"
        v-model="tableQuery.isHangup"
        clearable
        placeholder="请选择是否挂起"
        class="filter-item"
        style="width: 200px;"
      >
        <el-option
          v-for="item in is_hangup"
          :key="item.type"
          :label="item.label"
          :value="item.type"
        ></el-option>
      </el-select>

      <el-button
        size="small"
        @click="handleFilter"
        type="primary"
        class="filter-item"
        ref="btnQuery"
        >查询</el-button
      >
      <el-button
        @click="handleReset"
        size="small"
        type="primary"
        class="filter-item"
        ref="btnRefresh"
        >重置</el-button
      >
    </div>

    <el-table
      :data="tableData"
      :max-height="tableHeight"
      style="width: 100%;margin-bottom: 12px;"
    >
      <el-table-column
        label="id"
        prop="id"
        align="center"
        width="100px"
      ></el-table-column>
      <el-table-column
        label="数据源"
        prop="dataSource"
        align="center"
        min-width="120px"
      ></el-table-column>
      <el-table-column
        label="接口名称"
        prop="interfaceName"
        align="center"
        min-width="200px"
      ></el-table-column>
      <el-table-column
        label="接口地址"
        prop="interfaceAddress"
        align="center"
        min-width="320px"
      ></el-table-column>
      <el-table-column
        prop="retry"
        min-width="130px"
        label="失败重试阀值"
        align="center"
      >
      </el-table-column>
      <el-table-column
        label="失败是否挂起"
        min-width="130px"
        prop="isHangup"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.isHangup === 1 ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="100px">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            @click="handlePop('update', scope.row)"
            >编辑</el-button
          >
          <!-- <el-button type="text" size="mini" @click="handleDelete(scope.row.id)"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="tableQuery.currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="tableQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="actionType === 'add' ? '新增' : '编辑'"
      :visible.sync="formVisible"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      width="500px"
    >
      <el-form
        class="small-space"
        label-position="left"
        label-width="110px"
        style="width: 100%;"
      >
        <el-form-item label="数据源">
          <el-input
            size="small"
            type="text"
            v-model="createdItem.dataSource"
            placeholder="请输入数据源名称"
            :disabled="true"
            style="width: 100%;"
          ></el-input>
        </el-form-item>
        <el-form-item label="接口名称">
          <el-input
            size="small"
            type="text"
            v-model="createdItem.interfaceName"
            :disabled="true"
            placeholder="请输入接口名称"
            style="width: 100%"
          ></el-input>
        </el-form-item>
        <el-form-item label="接口地址">
          <el-input
            size="small"
            type="text"
            v-model="createdItem.interfaceAddress"
            placeholder="请输入接口地址"
            :disabled="true"
            style="width: 100%"
          ></el-input>
        </el-form-item>
        <el-form-item label="失败重试次数">
          <el-input-number
            v-model="createdItem.retry"
            controls-position="right"
            style="width: 160px;"
            size="small"
            :step="1"
            :step-strictly="true"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="失败后是否挂起">
          <el-checkbox
            :checked="createdItem.isHangup === 1 ? true : false"
            v-model="createdItem.isHangup"
          ></el-checkbox>
          <span style="color: rgb(0, 0, 0, 0.65);font-size: 12px;">
            勾选后如果数据源获取失败，则会挂起进件，然后需要人工干预重跑
          </span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="formVisible = false">取 消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="formSubmiting"
          @click="save"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Watch, Prop } from 'vue-property-decorator'
import TitleContainer from '@/components/title/TitleContainer.vue'
import {
  getNameMap,
  getTypeMap,
  getList,
  add,
  update,
  del
} from '@/api/risksystem/dataGateway/dataSource'
const defaultPage = {
  limit: 10,
  currentPage: 1
}
const defaultQuery = {
  dataSource: '',
  isHangup: ''
}
const defaultCreateQuery = {
  retry: 1,
  dataSource: '',
  interfaceName: '',
  interfaceAddress: '',
  isHangup: 0
}
@Component({
  name: 'dataSource',
  components: {
    //引用的组件在这里声明
    TitleContainer
  }
})
export default class extends Vue {
  private title = '风控管理-数据源管理'
  private data_source = []
  private is_hangup = [{ type: 1, label: '是' }, { type: 0, label: '否' }]
  private rule_typeOptions = [
    { type: 1, name: '每次进件调用' },
    { type: 2, name: '策略触发时调用' }
  ]
  private tableQuery = Object.assign({}, defaultQuery, defaultPage)
  private total = 0
  private tableData = []
  private tableHeight: any = null
  private tableLoading = true

  private createdItem: any = Object.assign({}, defaultCreateQuery)
  private actionType = 'add'
  private formVisible = false
  private formSubmiting = false
  created() {
    this.getNameMap()
    // this.getTypeMap()
    this.getList()
  }
  mounted() {
    this.init()
  }
  beforeDestroy() {
    // 摧毁监听事件
    window.onresize = null
  }
  // 表格高度
  private init() {
    var _this = this
    this.$nextTick(() => {
      this.tableHeight =
        window.innerHeight - (this.$refs.searchDiv as any).offsetHeight - 230
    })
    window.onresize = () => {
      this.$nextTick(() => {
        this.tableHeight =
          window.innerHeight - (this.$refs.searchDiv as any).offsetHeight - 230
      })
    }
  }
  // 搜索数据源获取
  private async getNameMap() {
    const { data } = await getNameMap()
    this.data_source = data
  }
  // private async getTypeMap() {
  //   const { data } = await getTypeMap()
  //   this.call_type = data
  // }
  private async getList() {
    const res: any = await getList(this.tableQuery)
    this.tableData = res.data.data
    this.total = res.data.total
  }
  // 查询、重置
  private handleFilter(val: string) {
    this.tableQuery.currentPage = 1
    this.getList()
  }
  // 跳转页码查询
  handleCurrentChange(val: any) {
    this.tableQuery.currentPage = val
    this.getList()
  }
  // size切换查询
  handleSizeChange(val: any) {
    this.tableQuery.limit = val
    this.getList()
  }
  private handleReset(val: string) {
    this.tableQuery = Object.assign({}, defaultQuery, defaultPage)
    this.getList()
  }
  // 新增|编辑
  private handlePop(action: any, data: any = {}) {
    // if (action === 'add') {
    //   // this.$log.event(this.title, 'add', this.title + '新增')
    //   this.createdItem = Object.assign({}, defaultCreateQuery)
    // }
    Object.assign(this.createdItem, data, {
      isHangup: data.isHangup === 1 ? true : false,
      is_retry: data.is_retry === 1
    })

    this.actionType = action
    this.formVisible = true
  }
  // 保存
  private async save() {
    let action = this.actionType
    let data: any = {}

    for (let i in defaultCreateQuery) {
      data[i] = this.createdItem[i]
    }
    data.id = this.createdItem.id
    data.isHangup = this.createdItem.isHangup === true ? 1 : 0

    const updateRes: any = await update(data)
    if (updateRes.code === 0) {
      this.$message.success(updateRes.message)
      this.formVisible = false
      this.getList()
    }
  }

  // 删除
  private async handeledel(val: any) {
    const res: any = await del(val)
    if (res.code === 0) {
      this.$message.success('删除成功')
      this.getList()
    } else {
      this.$message.error(res.message)
    }
  }
  private handleDelete(id: any) {
    // this.$log.event(this.title, 'delete', this.title + '删除')
    this.$confirm('确认删除该条配置？')
      .then(() => {
        // handle delete
        this.handeledel(id)
      })
      .catch(() => {})
  }
  private formatDate(now: any) {
    var year = now.getFullYear() //取得4位数的年份
    var month = now.getMonth() + 1 //取得日期中的月份，其中0表示1月，11表示12月
    var date = now.getDate() //返回日期月份中的天数（1到31）
    var hour = now.getHours() //返回日期中的小时数（0到23）
    var minute = now.getMinutes() //返回日期中的分钟数（0到59）
    var second = now.getSeconds() //返回日期中的秒数（0到59）
    return year + '-' + month + '-' + date
  }
}
</script>
<style scoped>
.components-container {
  padding: 20px;
}
</style>
